package com.lynn.springboot_demo.test;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * @author cl
 * @Date 2020/9/7 11:06
 * <p>
 * excel转pdf Jacob方法
 */
public class ExcelToPdfJacob {

    public static void main(String[] args) {

        String inFilePath = "C:\\Users\\Administrator\\Desktop\\电销中心运动报名1124-提报稿.xlsx";
        String outFilePath = "C:\\Users\\Administrator\\Desktop\\temp.pdf";
        ComThread.InitSTA(true);
        ActiveXComponent ax = new ActiveXComponent("Excel.Application");
        try {
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[]{
                            inFilePath,
                            new Variant(false),
                            new Variant(false)
                    },
                    new int[9]).toDispatch();
            //转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[]{
                    new Variant(0), //PDF格式=0
                    outFilePath,
                    new Variant(0)  //0=标准 (生成的PDF图片不会变模糊) 1=最小文件 (生成的PDF图片糊的一塌糊涂)
            }, new int[1]);

            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
        } catch (Exception es) {
        }
    }
}
